package com.efun.center.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    private final String ALLOW_ORIGIN = "*";
    private final String ALLOW_METHODS = "GET,HEAD,POST,PUT,DELETE,OPTIONS";
    private final String ALLOW_HEADERS = "content-type,pmtoken";
    private final String ALLOW_CREDENTIALS = "true";

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CorsInterceptor()).addPathPatterns("/**");
    }

    public class CorsInterceptor extends HandlerInterceptorAdapter {

        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            response.setHeader("Access-Control-Allow-Origin", ALLOW_ORIGIN);
            response.setHeader("Access-Control-Allow-Methods", ALLOW_METHODS);
            response.setHeader("Access-Control-Allow-Headers", ALLOW_HEADERS);
            response.setHeader("Access-Control-Allow-Credentials", ALLOW_CREDENTIALS);
            return true;
        }

    }

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseRegisteredSuffixPatternMatch(true);
    }

}
